import { request } from './request'
import { getEncodeURI } from './charset'
import { parseList, parseSearchUrl, formatUnicorn, v2 as _v2 } from './common'

function parseSearch (source: any, doc: string) {
  if (source.ruleSearch) {
    return v3.parseSearch(source, doc)
  } else {
    return v2.parseSearch(source, doc)
  }
}

async function downloadSearch (source: any, keyword: string, page = 1) {
  if (source.ruleSearch) {
    return v3.downloadSearch(source, keyword, page)
  } else {
    return v2.downloadSearch(source, keyword, page)
  }
}

const v3 = {
  parseSearch (source: any, doc: string) {
    const { bookList, ...restRules } = source.ruleSearch

    return parseList(doc, bookList, restRules)
  },

  async downloadSearch (source: any, keyword: string, page = 1) {
    let { url, options } = parseSearchUrl(source)
    const key = keyword
    url = getEncodeURI(formatUnicorn(url, { key, page }), options.charset)
    if (options.body) {
      options.body = getEncodeURI(formatUnicorn(options.body, { key, page }), options.charset)
    }
    const result = await request(url, options, source)
    return result
  }
}

const v2 = {
  parseSearch (source: any, doc: string) {
    const searchItemMap = {
      name: source.ruleSearchName,
      author: source.ruleSearchAuthor,
      kind: source.ruleSearchKind,
      lastChapter: source.ruleSearchLastChapter,
      introduce: source.ruleSearchIntroduce,
      coverUrl: source.ruleSearchCoverUrl,
      bookUrl: source.ruleSearchNoteUrl
      // infoInit: source.ruleBookInfoInit
    }
    return parseList(doc, source.ruleSearchList, searchItemMap)
  },

  async downloadSearch (source: any, keyword: string, page = 1) {
    let { url, options } = _v2.parseSearchUrl(source)
    const key = keyword
    url = getEncodeURI(formatUnicorn(url, { key, page }), 'utf-8')
    if (options.body) {
      options.body = formatUnicorn(options.body, { key, page })
    }
    const result = await request(url, options, source)
    return result
  }
}

export {
  parseSearch,
  downloadSearch
}
